﻿using System;
using System.Configuration;
using System.Collections.Specialized;
using WinHBM.Core.Net.Http;
using WinHBM.Core.Net.Sockets;
using WinHBM.Core.Bluetooth;
using InTheHand.Net.Sockets;
using System.Threading;
using WinHBM.Core.DB;
using WinHBM.Core.Task;
using System.Diagnostics;
using WinHBM.Utils;
using WinHBM.Config;
using System.Windows.Forms;
using System.IO;

namespace WinHBM
{
    public class Bootstrap
    {
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(Bootstrap));
        private static Thread taskThread;
        private static AppConfig config = AppConfig.Instance;

        public static void boot()
        {
            //判断系统架构，加载不同版本的SQLite库
            /*bool is64Bit;
            is64Bit = Environment.Is64BitOperatingSystem;
            string platform = is64Bit ? "x64" : "x86";
            string sourceFile = Application.StartupPath + @"\lib\System.Data.SQLite_"+ platform + ".dll";
            string destinationFile = Application.StartupPath + @"\System.Data.SQLite.dll";
            FileInfo file = new FileInfo(sourceFile);
            if (file.Exists)
            {
                // true is overwrite
                file.CopyTo(destinationFile, true);
            }*/
    
            //初始化数据库
            SQLiteHelper.install();
            

            //启动Flash和C#之前的Socket映射服务
            FlashSocketServer flashSocketServer = FlashSocketServer.Instance;
            flashSocketServer.Start(9901);

            //初始化Http配置
            WebRequest.CommonHeaders["Content-Type"] = "application/json";
            HttpClient client = HttpClient.Instance;
            client.RequestPrefix = config["apiHost"];
            client.BeforeRequestDispatcher += (request) => 
            {
                if (!String.IsNullOrEmpty(TokenHolder.Token))
                {
                    request.Headers["Authorization"] = "Bearer " + TokenHolder.Token;
                }
            };
            
            taskThread = new Thread(TaskThread);
            taskThread.Start();

            //进程退出监听
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

        }

        public static void TaskThread()
        {
            Uri uri = new Uri(config["apiHost"]);
            if (UtilPing.ping(uri.Host))
            {
                //初始化Task线程
                GetTokenTask.DoTask();
                UpdateBabyInfoTask.Start();
                UploadFlowerTask.Start();
            }
        }


        /// <summary>
        /// 进程退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Logger.Debug("OnMainProcessExited");
            GetTokenTask.Stop();
            UpdateBabyInfoTask.Stop();
            UploadFlowerTask.Stop();

            //关闭软键盘
            UtilSoftKeyBoard.closeSoftKey();
        }

        
    }
}
